import { request } from './index'
import type { Issue } from '@/types'

export const issueApi = {
  // 获取所有问题
  getAll(): Promise<Issue[]> {
    return request.get('/issues')
  },

  // 根据ID获取问题
  getById(id: number): Promise<Issue> {
    return request.get(`/issues/${id}`)
  },

  // 创建问题
  create(data: Omit<Issue, 'id' | 'createdAt' | 'updatedAt'>): Promise<Issue> {
    return request.post('/issues', data)
  },

  // 更新问题
  update(id: number, data: Partial<Issue>): Promise<Issue> {
    return request.put(`/issues/${id}`, data)
  },

  // 删除问题
  delete(id: number): Promise<void> {
    return request.delete(`/issues/${id}`)
  },

  // 根据项目ID获取问题
  getByProject(projectId: number): Promise<Issue[]> {
    return request.get(`/issues/project/${projectId}`)
  },

  // 获取分配给我的问题
  getMyAssigned(): Promise<Issue[]> {
    return request.get('/issues/assigned-to-me')
  },

  // 获取我报告的问题
  getMyReported(): Promise<Issue[]> {
    return request.get('/issues/reported-by-me')
  },

  // 根据状态获取问题
  getByStatus(status: string): Promise<Issue[]> {
    return request.get(`/issues/status/${status}`)
  },

  // 根据优先级获取问题
  getByPriority(priority: string): Promise<Issue[]> {
    return request.get(`/issues/priority/${priority}`)
  },

  // 更新问题状态
  updateStatus(id: number, status: string): Promise<Issue> {
    return request.patch(`/issues/${id}/status`, { status })
  },

  // 分配问题
  assign(id: number, assigneeId: number): Promise<Issue> {
    return request.patch(`/issues/${id}/assign`, { assigneeId })
  },

  // 解决问题
  resolve(id: number, resolution: string): Promise<Issue> {
    return request.patch(`/issues/${id}/resolve`, { resolution })
  },

  // 搜索问题
  search(keyword: string): Promise<Issue[]> {
    return request.get(`/issues/search?keyword=${keyword}`)
  },

  // 获取问题评论
  getComments(id: number): Promise<any[]> {
    return request.get(`/issues/${id}/comments`)
  },

  // 添加问题评论
  addComment(id: number, content: string): Promise<any> {
    return request.post(`/issues/${id}/comments`, { content })
  },

  // 上传问题附件
  uploadAttachment(id: number, file: File): Promise<{ url: string }> {
    const formData = new FormData()
    formData.append('file', file)
    return request.post(`/issues/${id}/attachments`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 关闭问题
  close(id: number): Promise<Issue> {
    return request.patch(`/issues/${id}/close`)
  },

  // 重新打开问题
  reopen(id: number): Promise<Issue> {
    return request.patch(`/issues/${id}/reopen`)
  }
}